import {
  unitList
} from '../../apis/user';
const app = getApp();

Page({
  data: {
    list: [],
    inputValue: '',
    isSearch: false,
    searchList: [],
    other: {
      unitId: -1,
      unitName: '其他单位'
    }
  },

  onLoad() {
    this.getUnitList();
  },

  getUnitList() {
    unitList().then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        rows.forEach(v => {
          if (v.unitId === -1) {
            this.setData({
              other: v
            });
          };
        });
        this.setData({
          list: rows
        });
      };
    });
  },

  // 选择单位
  selectUnit(e) {
    let {
      item
    } = e.currentTarget.dataset;
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.setData({
      'form.unitId': item.unitId,
      'form.unit': item.unitName
    });
    if (item.unitId === -1) {
      prevPage.setData({
        'form.unitExtra': ''
      });
    };
    wx.navigateBack({
      delta: 1
    });
  },

  handleInput(e) {
    let {
      value
    } = e.detail;

    if (value === '') {
      this.setData({
        inputValue: '',
        isSearch: false,
        searchList: []
      });
    } else {
      let list = this.data.list.filter(v => value.split('').every(val => new RegExp(val).test(v.unitName)));
      this.setData({
        inputValue: value,
        isSearch: true,
        searchList: list
      });
    };
  }
})